<?php

use xingwenge\canal_php\CanalClient;
use xingwenge\canal_php\CanalConnectorFactory;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;

require_once __DIR__ . '/vendor/autoload.php';

ini_set('display_errors', 'On');
error_reporting(E_ALL);

$config = require_once __DIR__ . '/configs/config.php';

$instanceName = 'yopurmaqInformation';

$instanceConfig = require_once __DIR__ . '/configs/' . $instanceName . '.php';
$HandlerClass = "\\Handlers\\" . ucfirst($instanceName) . "Handler";

$logFilePath = __DIR__ . '/logs/' . $instanceName . '.log';
$logMaxAgeDays = $config['log']['maxAgeDays'];
$log = new Logger('canal-php-client');
$log->pushHandler(new StreamHandler($logFilePath, Logger::INFO));

try {

  $client = CanalConnectorFactory::createClient(CanalClient::TYPE_SOCKET_CLUE);

  $client->connect($instanceConfig['canal']['address'], $instanceConfig['canal']['port']);
  $client->checkValid();
  $client->subscribe(
    $instanceConfig['canal']['instance']['client_id'],
    $instanceConfig['canal']['instance']['name'], 
    $instanceConfig['canal']['instance']['filter']['regex']
  );
  
  $handler = new $HandlerClass($instanceName, $instanceConfig['elasticsearch']['hosts'], $log);

  echo 'Client V3 is Running...', PHP_EOL;
  echo 'CUSTOMER HANDLER:', $HandlerClass, PHP_EOL;
  
  $count = 0;
  while (true) {
    $currentTimestamp = time();
    $logMaxAgeSeconds = $logMaxAgeDays * 24 * 60 * 60;
    $logMaxAgeSeconds = 10;
    
    if (file_exists($logFilePath) && is_file($logFilePath)) {
      $fileModifiedTime = filemtime($logFilePath);
      if ($currentTimestamp - $fileModifiedTime > $logMaxAgeSeconds) {
        //删除大于30天的日志
        unlink($logFilePath);

        // 创建新的空日志文件
        file_put_contents($logFilePath, '');

        // 更新日志处理器的文件路径
        $log->popHandler();
        $log->pushHandler(new StreamHandler($logFilePath, Logger::INFO));
      }
    }

    $message = $client->get(100);
    if ($entries = $message->getEntries()) {
      foreach ($entries as $entry) {
        $handler->syncData($entry);
      }
    }
    sleep(3);
  }

  $client->disConnect();
} catch (\Exception $e) {
  // echo 'main exception: ', PHP_EOL;
  // echo $e->getMessage(), PHP_EOL;
  $errMsg = $e->getMessage();
  $log->error('main exception: ' . $errMsg);

  for ($t = 0;$t < 3;$t++) {
    send_error_email($errMsg, $log);
    sleep(60);
  }
}

